package com.training1.core.modules.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.training1.core.common.entity.BOXUserEntity;
import com.training1.core.common.entity.RespJson;
import com.training1.core.common.global.signIn.BOXLoginInfoUtil;
import com.training1.core.common.utils.framework.RespJsonFactory;
import com.training1.core.common.utils.security.MD5;
import com.training1.core.modules.dao.BOXUserEntityDao;

/**
 * 登陆类
 * @author hl
 *
 */
@Service
@Transactional
public class BOXLoginService {

	private static final Logger log = LoggerFactory.getLogger(BOXLoginService.class);
	
	@Autowired
	private BOXUserEntityDao buserDao;
	
	public RespJson login(HttpServletRequest request,BOXUserEntity entity){
		
		//账号密码判定
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", entity.getUserId());
		BOXUserEntity user = buserDao.findUser(map);
		if(user!=null){
			log.debug("账号验证成功");
			try {
				String password = MD5.getMD5(entity.getPassword());
				if(user.getPassword().equals(password)){
					log.debug("密码验证成功");
					BOXLoginInfoUtil.setLoginInfoToSession(request, user, "");
					return RespJsonFactory.buildSuccess();
				}else {
					return RespJsonFactory.buildFailure("login.error");
				}
			} catch (Exception e) {
				log.debug("账号密码验证失败", e);
			}
		}
		return RespJsonFactory.buildFailure("login.error");
	}
	
	public RespJson passwordUpdate(HttpServletRequest request, String password, String newpassword){
		//获取session中存入的id
		Integer id = BOXLoginInfoUtil.getLoginInfo().getLoginId();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		BOXUserEntity user = buserDao.get(id);
		//获取原密码
		String userPW = user.getPassword();
		if(userPW.equals(MD5.getMD5(password))){
			log.debug("密码验证成功");
			//密码修改
			newpassword = MD5.getMD5(newpassword);
			map.put("newpassword", newpassword);
			buserDao.updatePassword(map);
			
			return RespJsonFactory.buildSuccess();
		}else{
			//密码不正确
			log.debug("密码验证失败");
			return RespJsonFactory.buildFailure("login.passwordError");
		}
		
	}
	public int getUserRole(Map<String,Object> map){
		return buserDao.getUserRole(map);
	}
}
